/*******************************************************************************
 * Copyright 2011-2013 Sergey Tarasevich
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.yeook.ymax.ui.activitys;

import java.io.File;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.yeook.ymax.R;
import com.yeook.ymax.app.ApplicationYMAX;
import com.yeook.ymax.db.Database;
import com.yeook.ymax.ui.activitys.Constants.Extra;
import com.yeook.ymax.ui.entity.WallaperView;
import com.yeook.ymax.ui.wallaper.WallaperPhotographs;

/**
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 */
public class ImagePagerActivity extends Activity {
	public ImageLoader imageLoader = ImageLoader.getInstance();
	private static final String STATE_POSITION = "STATE_POSITION";
	private static final long ANIM_VIEWPAGER_DELAY = 3000;

	private DisplayImageOptions options;

	private Handler mHandler;

	private ArrayList<WallaperView> wallaperViews = new ArrayList<WallaperView>();

	private ViewPager pager;

	private View menuLayOut;
	
	private View headerLayOut;

	private View autoPlayMenu;

	private View menu;
	
	private View backMenu;

	private PopupWindow menuPop = null;

	private boolean isAutoPlay = false;

	//private Bitmap currentImage = null;
	
	//private String cuurrentImageUrl = null;

	private File mTempFile;

	//private ImageView imageView;

	public static Intent newInstance(Activity activity, int pos,
			ArrayList<WallaperView> wallaperViews) {
		Intent intent = new Intent(activity, ImagePagerActivity.class);
		//intent.putExtra(Extra.IMAGES, wallaperViews);
		intent.putExtra(Extra.IMAGE_POSITION, pos);
		return intent;
	}

	private void startAutoPlay() {
		isAutoPlay = true;
		if (h != null) {
			h.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
		}
	}

	private void stopAutoPlay() {
		isAutoPlay = false;
		if (h != null) {
			h.removeCallbacks(animateViewPager);
		}
	}

	private Handler h = new Handler();
	private Runnable animateViewPager = new Runnable() {
		public void run() {
			if (wallaperViews != null && wallaperViews.size() > 0) {
				pager.setCurrentItem((pager.getCurrentItem() + 1)
						% wallaperViews.size(), true);
				// h.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
			}
		}
	};

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setTitle(this.getString(R.string.view_image));
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
//		ColorDrawable color = new ColorDrawable(Color.BLACK);
//		color.setAlpha(128);
//		getSupportActionBar().setBackgroundDrawable(color);
//		getSupportActionBar().setLogo(R.drawable.ic_live_wallpaper);
//		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//		getSupportActionBar().hide();
		
		mHandler = new Handler();

		setContentView(R.layout.ac_image_pager);
		Bundle bundle = getIntent().getExtras();
		wallaperViews = ResponsiveUIActivity.wallaperViews;//(ArrayList<WallaperView>) getIntent().getSerializableExtra(Extra.IMAGES);
		// XmlLoader xmlLoader = new XmlLoader();
		// String[] imageUrls = xmlLoader.getImageUrls(xmlLoader.praseXml());
		int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
		// int pagerPosition = 20;
		if (savedInstanceState != null) {
			pagerPosition = savedInstanceState.getInt(STATE_POSITION);
		}

		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.ic_empty)
				.showImageOnFail(R.drawable.ic_error).resetViewBeforeLoading().cacheInMemory()
				.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new FadeInBitmapDisplayer(300)).build();

		pager = (ViewPager) findViewById(R.id.image_pager);
		pager.setAdapter(new ImagePagerAdapter(wallaperViews));
		pager.setCurrentItem(pagerPosition);

		menuLayOut = (View) findViewById(R.id.pager_menu);
		// menu.setBackgroundColor(Color.BLACK);
		menuLayOut.getBackground().setAlpha(128);
		// this.getWindow().setBackgroundDrawableResource(android.R.color.black);
		
		headerLayOut = (View) findViewById(R.id.image_header_menu);
		headerLayOut.getBackground().setAlpha(128);

		autoPlayMenu = (View) findViewById(R.id.auto_play_menu);
		autoPlayMenu.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (isAutoPlay) {
					stopAutoPlay();
				} else {
					startAutoPlay();
				}

			}
		});

		menu = (View) findViewById(R.id.image_main_menu);
		menu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try{
					String pageImageUrl = wallaperViews.get(pager.getCurrentItem()).getFileName();
					if (pageImageUrl != null) {
						Intent intent = new Intent();
						intent.setClassName(ImagePagerActivity.this,
								WallaperPhotographs.class.getName());
						intent.putExtra("imageUrl", pageImageUrl);
						//intent.putExtra("data", currentImage);
						ImagePagerActivity.this
								.startActivity(intent);
					}
				}catch(Exception ex)
				{
					Log.e("YMAX", ex.getLocalizedMessage(), ex);
				}
			}
			
		});
		
		backMenu = (View) findViewById(R.id.live_wallpaper_image);
		
		//backMenu.bringToFront();
		
		backMenu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				finish();
				
			}
		});
		
//		menu.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				View paopaoView = getLayoutInflater().inflate(
//						R.layout.pop_menu, null);
//				paopaoView.getBackground().setAlpha(100);
//				// 这里最关键，不在pop的View的里面找到相映的ID，还真不好关闭popWin
//				Button pop_play_btn = (Button) paopaoView
//						.findViewById(R.id.set_wallaper);
//
//				menuPop = new PopupWindow(paopaoView,
//						RelativeLayout.LayoutParams.WRAP_CONTENT,
//						RelativeLayout.LayoutParams.WRAP_CONTENT);
//
//				menuPop.setBackgroundDrawable(new BitmapDrawable());
//
//				menuPop.setFocusable(true);
//				// 设置允许在外点击消失
//		        menuPop.setOutsideTouchable(true);
//				// 
//				paopaoView.setFocusableInTouchMode(true);  
//				paopaoView.setOnKeyListener(new OnKeyListener() {  
//					@Override  
//					public boolean onKey(View v, int keyCode, KeyEvent event) {  
//						// TODO Auto-generated method stub  
//						if ((keyCode == KeyEvent.KEYCODE_MENU)&&(menuPop.isShowing())) {  
//                             
//							menuPop.dismiss();// 这里写明模拟menu的PopupWindow退出就行  
//							return true;  
//						}  
//						return false;  
//					}
// 
//				}); 
//
//				// menuPop.showAtLocation(menu, Gravity.LEFT, 0, 0);
//				int[] location = new int[2];
//				v.getLocationOnScreen(location);
//				
//				//menuPop.showAsDropDown(v, 0, - ImagePagerActivity.this.getResources().getDimensionPixelSize(250));
//				menuPop.showAsDropDown(v, 0, - 300);
//
////				menuPop.showAtLocation(menu, Gravity.NO_GRAVITY, location[0],
////						location[1] + 450);
//				
//				pop_play_btn.setOnClickListener(new OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						ContentResolver cR = ImagePagerActivity.this.getContentResolver();
//						if(currentImage != null){
//
//							Intent intent = new Intent();
//							intent.setClassName(ImagePagerActivity.this,
//									WallaperPhotographs.class.getName());
//							//intent.setDataAndType(null, null);
//					         intent.putExtra("data", currentImage);
//	                         ((Activity) ImagePagerActivity.this).startActivity(intent);
//						}
//						closePop();
//					}
//				});
//			}
//		});
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(STATE_POSITION, pager.getCurrentItem());
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		closePop();
		return super.onTouchEvent(event);
	}

	private void closePop() {
		if (null != menuPop) {
			menuPop.dismiss();
		}
	}

//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		switch (item.getItemId()) {
//		case android.R.id.home:
//			finish();
//			return true;
//		}
//		return super.onOptionsItemSelected(item);
//	}

	@Override
	public void onResume() {
		super.onResume();
		//getSupportActionBar().show();
		menuLayOut.setVisibility(View.VISIBLE);
		headerLayOut.setVisibility(View.VISIBLE);
		hideActionBarDelayed(mHandler);
		if (isAutoPlay) {
			h.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (h != null) {
			h.removeCallbacks(animateViewPager);
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			if (mHandler != null) {
				mHandler.removeCallbacks(hideActionBar);
			}
			
			stopAutoPlay();

			//getSupportActionBar().show();
			menuLayOut.setVisibility(View.VISIBLE);
			headerLayOut.setVisibility(View.VISIBLE);
		}
		if (ev.getAction() == MotionEvent.ACTION_UP) {
			//h.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
			hideActionBarDelayed(mHandler);
		}

		return super.dispatchTouchEvent(ev);
	}
	
	private Runnable hideActionBar = new Runnable() {
		public void run() {
			//getSupportActionBar().hide();
			menuLayOut.setVisibility(View.GONE);
			headerLayOut.setVisibility(View.GONE);
		}
	};

	private void hideActionBarDelayed(Handler handler) {
		handler.postDelayed(hideActionBar, 4000);
	}

	private class ImagePagerAdapter extends PagerAdapter {

		private ArrayList<WallaperView> wallaperViews;
		private LayoutInflater inflater;

		ImagePagerAdapter(ArrayList<WallaperView> _wallaperViews) {
			this.wallaperViews = _wallaperViews;
			inflater = getLayoutInflater();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public void finishUpdate(View container) {
		}

		@Override
		public int getCount() {
			return wallaperViews.size();
		}

		@Override
		public Object instantiateItem(ViewGroup view, int position) {
			View imageLayout = inflater.inflate(R.layout.item_pager_image,
					view, false);
			ImageView _imageView = (ImageView) imageLayout
					.findViewById(R.id.wallaper_image);
			final ProgressBar spinner = (ProgressBar) imageLayout
					.findViewById(R.id.loading);
			
			_imageView.setTag(wallaperViews.get(position).getUniqueId());

			imageLoader.displayImage(ApplicationYMAX.DEFAULTWEBSERVIC + wallaperViews.get(position).getFileName(), _imageView, options,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
							spinner.setVisibility(View.VISIBLE);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							String message = null;
							switch (failReason.getType()) {
							case IO_ERROR:
								message = "Input/Output error";
								break;
							case DECODING_ERROR:
								message = "Image can't be decoded";
								break;
							case NETWORK_DENIED:
								message = "Downloads are denied";
								break;
							case OUT_OF_MEMORY:
								message = "Out Of Memory error";
								break;
							case UNKNOWN:
								message = "Unknown error";
								break;
							}
							Toast.makeText(ImagePagerActivity.this, message,
									Toast.LENGTH_SHORT).show();

							spinner.setVisibility(View.GONE);
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, final Bitmap loadedImage) {
							//currentImage = loadedImage;
							//cuurrentImageUrl = imageUri;
							//imageView = (ImageView)view;
							spinner.setVisibility(View.GONE);
							if (isAutoPlay) {
								h.postDelayed(animateViewPager,
										ANIM_VIEWPAGER_DELAY);
							}
							
							//添加历史记录
							try{
								Database.getInstance().insertHistory((Integer)view.getTag(), "wallpaper");
							}catch(Exception ex)
							{
								ex.printStackTrace();
							}
						}
					});

			((ViewPager) view).addView(imageLayout, 0);
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View container) {
		}
	}
}